import { Suspense, useState, useEffect } from 'react';
import { EllipsisOutlined } from '@ant-design/icons';
import { Col, Dropdown, Menu, Row } from 'antd';
import { GridContent } from '@ant-design/pro-layout';
import IntroduceRow from './components/IntroduceRow';
import SalesCard from './components/SalesCard';
import {
  queryDayRule,
  queryWeekRule,
  queryMonthRule,
  queryYearRule,
  chartsService,
} from './service';
import PageLoading from './components/PageLoading';
import { getTimeDistance } from './utils/utils';
import moment from 'moment';
import styles from './style.less';

const DashboardAnalysis = (props) => {
  const { storeId } = props;
  const [salesType, setSalesType] = useState('all');
  const [currentTabKey, setCurrentTabKey] = useState('');
  const [rangePickerValue, setRangePickerValue] = useState(getTimeDistance('today'));
  const [data, setData] = useState();
  const [dayData, setDayData] = useState();
  const [weekData, setWeekData] = useState();
  const [monthData, setMonthData] = useState();
  const [yearData, setYearData] = useState();
  const [loading, setLoading] = useState();
  const [salesData, setSalesData] = useState([]);

  const handleInnerSetData = (payload) => {
    setSalesData([
      { name: '开卡', count: payload.totalOpenCardCount, amount: payload.totalOpenCard },
      { name: '充值', count: payload.totalRechargeCount, amount: payload.totalRecharge },
      { name: '消费', count: payload.totalConsumeCount, amount: payload.totalConsume },
    ]);
  };
  const handleSetSalesData = (type) => {
    switch (type) {
      case 'today':
        handleInnerSetData(dayData);
        break;
      case 'week':
        handleInnerSetData(weekData);
        break;
      case 'month':
        handleInnerSetData(monthData);
        break;
      case 'year':
        handleInnerSetData(yearData);
        break;
    }
  };
  const searchDayInfo = async (payload) => {
    const res = await queryDayRule(storeId, payload);
    const { data } = res;
    handleInnerSetData(data);
  };
  const getDayInfo = async (payload) => {
    const res = await queryDayRule(storeId, payload);
    const { data } = res;
    handleInnerSetData(data);
    setDayData(data);
  };
  const getWeekInfo = async (payload) => {
    const res = await queryWeekRule(storeId, payload);
    const { data } = res;
    setWeekData(data);
  };
  const getMonthInfo = async (payload) => {
    const res = await queryMonthRule(storeId, payload);
    const { data } = res;
    setMonthData(data);
  };
  const getYearInfo = async (payload) => {
    const res = await queryYearRule(storeId, payload);
    const { data } = res;
    setYearData(data);
  };
  const onDayChange = (date, dateString) => {
    if (date) {
      getDayInfo({ startTime: dateString, endTime: dateString });
    }
  };
  const onWeekChange = (date, dateString) => {
    if (date) {
      const startTime = moment(date).day(0).format('YYYY-MM-DD');
      const endTime = moment(date).day(6).format('YYYY-MM-DD');
      getWeekInfo({ startTime, endTime });
    }
  };
  const onMonthChange = (date, dateString) => {
    if (date) {
      const nowDate = moment(date).day(1).format('YYYY-MM-DD');
      const dateArray = nowDate.split('-');
      const startTime = moment(new Date(dateArray[0], Number(dateArray[1]) - 1, 1)).format(
        'YYYY-MM-DD',
      ); // 当月第一天
      const endTime = moment(new Date(dateArray[0], Number(dateArray[1]), 0)).format('YYYY-MM-DD'); // 当月最后一天
      getMonthInfo({ startTime, endTime });
    }
  };
  const onYearChange = (date, dateString) => {
    if (date) {
      const startTime = `${dateString}-01-01`;
      const endTime = `${dateString}-12-31`;
      getYearInfo({ startTime, endTime });
    }
  };
  const chartsChange = (time, date, payload) => {
    chartsService(time, date, {
      startTime: payload?.startTime,
      endTime: payload?.endTime,
      storeId: storeId,
    })
      .then((res) => {
        const { code } = res;
        return code === 0 ? handleInnerSetData(res.data) : null;
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const selectDate = (type) => {
    handleSetSalesData(type);
    setRangePickerValue(getTimeDistance(type));
    const nowDate = moment(new Date()).day(1).format('YYYY-MM-DD');
    const toDay = moment(new Date()).format('YYYY-MM-DD');
    const dateArray = nowDate.split('-');
    const startTime = moment(new Date()).day(1).format('YYYY-MM-DD');
    const endTime = moment(new Date()).day(7).format('YYYY-MM-DD');
    const monthTime = moment(new Date(dateArray[0], Number(dateArray[1]) - 1, 1)).format(
      'YYYY-MM-DD',
    ); // 当月第一天
    const yearTime = `${new Date().getFullYear()}-01-01`;
    switch (type) {
      case 'today':
        chartsChange('day', toDay);
        break;
      case 'week':
        chartsChange(type, '', { startTime, endTime });
        break;
      case 'month':
        chartsChange(type, monthTime);
        break;
      case 'year':
        chartsChange(type, yearTime);
        break;
      default:
        break;
    }
  };
  useEffect(async () => {
    await getDayInfo();
    await getWeekInfo();
    await getMonthInfo();
    await getYearInfo();
    await chartsChange('day',moment(new Date()).format('YYYY-MM-DD'))
  }, [storeId]);

  const handleRangePickerChange = (value, exact) => {
    if (value) {
      const [startTime, endTime] = exact;
      searchDayInfo({
        startTime,
        endTime,
      });
    }

    setRangePickerValue(value);
  };

  const isActive = (type) => {
    if (!rangePickerValue) {
      return '';
    }

    const value = getTimeDistance(type);

    if (!value) {
      return '';
    }

    if (!rangePickerValue[0] || !rangePickerValue[1]) {
      return '';
    }

    if (
      rangePickerValue[0].isSame(value[0], 'day') &&
      rangePickerValue[1].isSame(value[1], 'day')
    ) {
      return styles.currentDate;
    }

    return '';
  };

  let salesPieData;

  // if (salesType === 'all') {
  //   salesPieData = data?.salesTypeData;
  // } else {
  //   salesPieData = salesType === 'online' ? data?.salesTypeDataOnline : data?.salesTypeDataOffline;
  // }

  const menu = (
    <Menu>
      <Menu.Item>操作一</Menu.Item>
      <Menu.Item>操作二</Menu.Item>
    </Menu>
  );
  const dropdownGroup = (
    <span className={styles.iconGroup}>
      <Dropdown overlay={menu} placement="bottomRight">
        <EllipsisOutlined />
      </Dropdown>
    </span>
  );

  const handleChangeSalesType = (e) => {
    setSalesType(e.target.value);
  };

  const handleTabChange = (key) => {
    setCurrentTabKey(key);
  };

  const activeKey = currentTabKey || (data?.offlineData[0] && data?.offlineData[0].name) || '';
  return (
    <GridContent>
      <>
        <Suspense fallback={<PageLoading />}>
          <IntroduceRow
            selectDay={onDayChange}
            selectWeek={onWeekChange}
            selectMonth={onMonthChange}
            selectYear={onYearChange}
            loading={loading}
            // visitData={data?.visitData || []}
            dayData={dayData}
            weekData={weekData}
            monthData={monthData}
            yearData={yearData}
          />
        </Suspense>

        <Suspense fallback={null}>
          <SalesCard
            rangePickerValue={rangePickerValue}
            salesData={salesData || []}
            isActive={isActive}
            handleRangePickerChange={handleRangePickerChange}
            loading={loading}
            selectDate={selectDate}
          />
        </Suspense>

        {/* <Row
          gutter={24}
          style={{
            marginTop: 24,
          }}
        >
          <Col xl={12} lg={24} md={24} sm={24} xs={24}>
            <Suspense fallback={null}>
              <TopSearch
                loading={loading}
                visitData2={data?.visitData2 || []}
                searchData={data?.searchData || []}
                dropdownGroup={dropdownGroup}
              />
            </Suspense>
          </Col>
          <Col xl={12} lg={24} md={24} sm={24} xs={24}>
            <Suspense fallback={null}>
              <ProportionSales
                dropdownGroup={dropdownGroup}
                salesType={salesType}
                loading={loading}
                salesPieData={salesPieData || []}
                handleChangeSalesType={handleChangeSalesType}
              />
            </Suspense>
          </Col>
        </Row> */}

        {/* <Suspense fallback={null}>
          <OfflineData
            activeKey={activeKey}
            loading={loading}
            offlineData={offlineData || []}
            offlineChartData={offlineChartData || []}
            handleTabChange={handleTabChange}
          />
        </Suspense> */}
      </>
    </GridContent>
  );
};

export default DashboardAnalysis;
